const expres = require('express');
const router = expres.Router();
const { User } = require('../../models');
const { Op } = require('sequelize');
const { BadRequestError, UnauthorizedError } = require('../../utils/errors');
const { successResponse, failureResponse } = require('../../utils/responses');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

router.post('/sign_in', async function(req, res, next) {
  try {
    const { login, password } = req.body;
    if (!login) {
      throw new BadRequestError('邮箱或用户名必须填写');
    }
    if (!password) {
      throw new BadRequestError('密码必须填写');
    }
    const condition = {
      where: {
        [Op.or]: [
          { email: login },
          { username: login }
        ]
      }
    };
    const user = await User.findOne(condition);
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedError('密码错误，请重试');
    }
    if (!user) {
      throw new BadRequestError('用户不存在，请检查邮箱或用户名');
    }
    // role: 100 是管理员
    if (user.role !== 100) {
      throw new UnauthorizedError('您没有权限登录管理员后台');
    }
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      process.env.SECRET, // 密钥
      { expiresIn: '30d' }, // 过期时间
    );
    successResponse(res, '登录成功', { token });
  } catch (error) {
    failureResponse(res, error);
  }
})

module.exports = router;